﻿/*
 * Copyright (C) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public GameObject ExplosionPrefab;

    private const float MinSpeed = 50.0f;
    private const float MaxSpeed = 100.0f;

    private float speed;
    private GameObject targetComplex = null;

    // if enemy gets below this Y coordinate, its target city explodes
    private const float TriggerY = 100.0f;

    void Setup(GameObject targetComplex) {
        this.targetComplex = targetComplex;
        speed = Random.Range(MinSpeed, MaxSpeed);
        gameObject.transform.LookAt(targetComplex.transform.position);
    }


    // Update is called once per frame
    void Update () {
        // move towards our target
        Vector3 v = (targetComplex.transform.position - gameObject.transform.position).normalized * speed;
        gameObject.transform.Translate(v * Time.deltaTime, Space.World);

        // make sure we're in the spherical shell where the player missiles explode
        gameObject.transform.position = gameObject.transform.position.normalized * MissileController.DistToExplode;

        // make sure we're pointing at our target
        gameObject.transform.LookAt(targetComplex.transform.position);

        // are we below the trigger altitude?
        if (gameObject.transform.position.y < TriggerY) HitTarget();
    }

    public static void SpawnEnemy(GameObject prefab, GameObject spawnPoint, GameObject targetComplex) {
        GameObject enemy = (GameObject)GameObject.Instantiate(prefab, spawnPoint.transform.position,
            Quaternion.identity);
        enemy.GetComponent<EnemyController>().Setup(targetComplex);
    }

    public void TakeExplosionDamage() {
        SelfDestruct();
        GameManager.Instance.AddScore(50);
    }

    void HitTarget() {
        targetComplex.GetComponent<ComplexController>().TakeEnemyDamage();
        SelfDestruct();
    }

    void SelfDestruct() {
        GameObject.Instantiate(ExplosionPrefab, gameObject.transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}
